package com.fxz.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fxz.common.exception.CaptchaException;
import com.fxz.common.lang.Const;
import com.fxz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验验证码是否正确 (在校验用户名、密码之前)
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        //获取请求url
        String url =  httpServletRequest.getRequestURI();

        //拦截 校验验证码
        if("/login".equals(url)&&httpServletRequest.getMethod().equals("POST")){

            //如果不正确 跳转到认证失败处理器
            try{
                validate(httpServletRequest);
            }catch (CaptchaException e){
                //交给认证失败的处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }
        }
        //继续走过滤链
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    //校验验证码的逻辑
    private void validate(HttpServletRequest httpServletRequest) {

        String code =  httpServletRequest.getParameter("code");
        String key  =  httpServletRequest.getParameter("token");

        if(StringUtils.isBlank(code)||StringUtils.isBlank(key)){
            throw new CaptchaException("验证码错误!");
        }


        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key))){
            throw new CaptchaException("验证码错误!");
        }

        //一次性使用 去掉redis存的验证码
        redisUtil.hdel(Const.CAPTCHA_KEY,key);
    }
}
